from amscms.core.forms import UserSignupForm
from django.conf import settings
from django.contrib.sites.models import Site
from django.core import mail
from django.test import TestCase
from django.utils.translation import ugettext as _, activate
import re

class UserSignupFormTest(TestCase):
    
    
    fixtures = ['authtestdata.json']
    
    USER_DATA = {
        'username': 'jsmith',
        'password1': 'test123',
        'password2': 'test123',
        'first_name': 'Jo',
        'last_name': 'Smith',
        'email': 'jo.smith@example.com',
     }

    def setUp(self):
        # TODO:: Below config should pass the test, but it does not!
        # Note: set RECAPTCHA_VALIDATION_OVERRIDE to True 
        # in setting_security.py will pass the test
        # Skip the reCaptcha validation
        settings.RECAPTCHA_VALIDATION_OVERRIDE = True
        activate('en')
    
    def test_user_already_exists(self):
        data = {
            'username': 'testclient',
            'password1': 'test123',
            'password2': 'test123',
            }
        form = UserSignupForm(data)
        self.assertFalse(form.is_valid())
        self.assertEqual(form["username"].errors,
                         [u'User with this Username already exists.'])

    def test_invalid_data(self):
        data = {
            'username': 'jsmith!',
            'password1': 'test123',
            'password2': 'test123',
            }
        form = UserSignupForm(data)
        self.assertFalse(form.is_valid())
        self.assertEqual(form["username"].errors,
                         [u'This value may contain only letters, numbers and @/./+/-/_ characters.'])
    
    def test_password_verification(self):
        # The verification password if incorrect.
        data = {
            'username': 'jsmith',
            'password1': 'test123',
            'password2': 'test',
            }
        form = UserSignupForm(data)
        self.assertFalse(form.is_valid())
        self.assertEqual(form["password2"].errors,
                         [u"The two password fields didn't match."])
        
    def test_fields_required(self):
        # One (or all) fields weren't given
        data = {'username': 'jsmith'}
        form = UserSignupForm(data)
        self.assertFalse(form.is_valid())
        self.assertEqual(form['password1'].errors,
                             [u'This field is required.'])
        self.assertEqual(form['password2'].errors,
                             [u'This field is required.'])
        self.assertEqual(form['first_name'].errors,
                             [u'This field is required.'])
        self.assertEqual(form['last_name'].errors,
                             [u'This field is required.'])
        self.assertEqual(form['email'].errors,
                             [u'This field is required.'])
        
        data['password2'] = 'test123'
        form = UserSignupForm(data)
        self.assertFalse(form.is_valid())
        self.assertEqual(form["password1"].errors,
                         [u'This field is required.'])
        
    def test_success(self):
        # The success case.
        form = UserSignupForm(self.USER_DATA)
        self.assertTrue(form.is_valid())
        u = form.save()
        self.assertEqual(repr(u), '<User: jsmith>')
        
    def _test_activation_start(self):
        # Start by creating the email
        response = self.client.post('/core/signup/', self.USER_DATA)
        self.assertEquals(response.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        return self._read_signup_email(mail.outbox[0])
        
    def _read_signup_email(self, email):
        urlmatch = re.search(r"https?://[^/]*(/.*core/signup_active/\S*)", email.body)
        self.assert_(urlmatch is not None, "No activation URL found in sent email")
        return urlmatch.group(), urlmatch.group()[18:]
        
    def test_activation_valid(self):
        url, path = self._test_activation_start()
        response = self.client.get(path)
        self.assertEquals(response.status_code, 302)
    
    def test_email_translations_correctness(self):
        response = self.client.post('/core/signup/', self.USER_DATA)
        self.assertEquals(response.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        
        site_name = Site.objects.get_current()
         
        email = mail.outbox[0]
        self.assertEquals(email.subject, _(u'Account activation link for %(site_name)s'% {'site_name': site_name}))
        bodymatch = re.search(_(u'Account activation link for username:'), email.body)
        self.assert_(bodymatch is not None, "This text does not exist.")
        bodymatch2 = re.search(_(u'Please select below link to complete the registration.'), email.body)
        self.assert_(bodymatch2 is not None, "This text does not exist.")
        
        urlmatch = re.search(r"https?://[^/]*(/.*core/signup_active/\S*)", email.body)
        self.assert_(urlmatch is not None, "No activation URL found in sent email")
        path = urlmatch.group()[18:] 
        response = self.client.get(path)
        self.assertEquals(response.status_code, 302)
        self.assertEquals(len(mail.outbox), 2)
        
        email2 = mail.outbox[1]
        self.assertEquals(email2.subject, _(u"Registration was successful on %(site_name)s" % {'site_name': site_name, }))
        bodymatch3 = re.search(_(u'Now you are able to login into our website.'), email2.body)
        self.assert_(bodymatch3 is not None, "This text does not exist.")
        bodymatch4 = re.search(_(u"Your username, in case you've forgotten:"), email2.body)
        self.assert_(bodymatch4 is not None, "This text does not exist.")
